package com.hbwxz.user.service;

import com.hbwxz.common.response.CommonResponse;
import com.hbwxz.common.response.ResponseCode;
import com.hbwxz.common.response.ResponseUtils;
import com.hbwxz.user.pojo.User;
import com.hbwxz.user.processor.RedisCommonProcessor;
import com.hbwxz.user.repo.UserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserInfoService {

    @Autowired
    private RedisCommonProcessor redisCommonProcessor;

    @Autowired
    private UserRepository userRepository;

    public CommonResponse checkPhoneBindStatus(String personId) {
        User user = (User) redisCommonProcessor.get(personId);
        boolean isBind = false;
        if(user != null) {
            isBind = user.getUserPhone() != null;
            return ResponseUtils.okResponse(isBind);
        }
        Integer userId = Integer.valueOf(personId) - 10000000;
        Optional<User> userOptional = userRepository.findById(userId);
        if(userOptional.isPresent()) {
            isBind = userOptional.get().getUserPhone() != null;
            redisCommonProcessor.setExpiredDays(personId, userOptional.get(), 30);
            return ResponseUtils.okResponse(isBind);
        }
        return ResponseUtils.failResponse(ResponseCode.BAD_REQUEST.getCode(), null, "Invalid user!");
    }

    public CommonResponse bindPhoneNumber(String personId, String phoneNumber, String code) {
        //进行更新db就行了
        String cacheCode = String.valueOf(redisCommonProcessor.get(phoneNumber));
        if(StringUtils.isEmpty(cacheCode)) {
            return ResponseUtils.failResponse(ResponseCode.BAD_REQUEST.getCode(), null, "Phone code is expired!");
        }
        if(!cacheCode.equals(code)) {
            return ResponseUtils.failResponse(ResponseCode.BAD_REQUEST.getCode(), null, "Phone code is wrong!");
        }
        Integer userId = Integer.valueOf(personId) - 10000000;
        Optional<User> userOptional = userRepository.findById(userId);
        if(userOptional.isPresent()) {
            userRepository.updateUserPhoneById(phoneNumber, userId);
            redisCommonProcessor.remove(personId);
            return ResponseUtils.okResponse(null);
        }
        return ResponseUtils.failResponse(ResponseCode.BAD_REQUEST.getCode(), null, "Invalid User!");
    }
}
